package org.viva.service.cms;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Service;
import org.viva.admin.util.page.Page;
import org.viva.core.dao.BaseDAO;
import org.viva.entity.cms.Content;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("contentService")
public class ContentServiceImpl implements ContentService {

    @Resource
    private BaseDAO<Content> dao;

    @SuppressWarnings("unchecked")
    @Override
    public List<Content> getList(Map<String, Object> param) {
        Criteria criteria = dao.getCurrentSession().createCriteria(Content.class);
        criteria.add(Restrictions.eq("cgId", Long.parseLong(param.get("cgid") + "")));
        return criteria.list();
    }

    @Override
    public Content get(Long id) {
        return dao.get(Content.class, id);
    }

    @Override
    public Page getPage(Map<String, Object> param) {
        Page page = new Page(param);
        Criteria criteria = dao.getCurrentSession().createCriteria(Content.class);
        // 获取根据条件分页查询的总行数
        int rowCount = (int) ((long) criteria.setProjection(Projections.rowCount()).uniqueResult());
        ProjectionList proList = Projections.projectionList();// 设置投影集合
        proList.add(Projections.groupProperty("id"));
        proList.add(Projections.groupProperty("title"));
        proList.add(Projections.groupProperty("createDate"));
        criteria.setProjection(proList);
        criteria.setFirstResult((page.getPage() - 1) * page.getRows());
        criteria.setMaxResults(page.getRows());
        System.out.println(JSONArray.fromObject(criteria.list().get(0)));
        page.addDate(criteria.list(), rowCount);
        return null;
    }

    @Override
    public void up(Content content) {
        Content c = dao.get(Content.class, content.getId());
        c.setTitle(content.getTitle());
        c.setContent(content.getContent());
        c.setCreateDate(content.getCreateDate());
        c.setTags(content.getTags());
        c.setCgId(content.getCgId());
        {
            // 简介
            String A_INTRO = Jsoup.parse(c.getContent()).text();
            A_INTRO = A_INTRO.replaceAll("[\r\n]", "");
            A_INTRO = A_INTRO.substring(0, A_INTRO.length() > 300 ? 300 : A_INTRO.length());
            c.setIntro(A_INTRO);
        }
    }

    @Override
    public void add(Content content) {
        content.setCommCount(0L);
        content.setViewCount(0L);
        dao.saveOrUpdate(content);
    }

    @Override
    public void del(Long id) {
        dao.delete(dao.get(Content.class, id));
    }

}
